package com.daoeping.dao;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import com.daoeping.dao.AllDaoSupport;
import com.daoeping.data.Bzn_question;
import com.daoeping.data.Bzn_questionassigned;
import com.daoeping.domain.JsonData;
import com.daoeping.domain.Page;
import com.daoeping.domain.TableData;
import com.daoeping.util.ConverntJsonData;
import com.daoeping.util.TimeDiff;

public class Bzn_questionassignedDAO extends AllDaoSupport {
	
	public List<Bzn_questionassigned> findBzn_questionassignedList(Bzn_questionassigned bzn_questionassigned){
		return (List<Bzn_questionassigned>) selectDataByHQL("from Bzn_questionassigned bzn where bzn.bzn_question.id = "+bzn_questionassigned.getBzn_question().getId());
	}
	
	public boolean delBzn_questionassigned(JsonData jsonData , Bzn_questionassigned bzn_questionassigned){
		return updateDataByHQL("delete from Bzn_questionassigned bzn where bzn.usr_user.id in("+jsonData.getJsonData()+") and bzn.bzn_question.id = "+bzn_questionassigned.getBzn_question().getId());
	}
	public JsonData findBzn_questionassignedByUser(Page page, TableData tableData , Bzn_questionassigned bzn_questionassigned){
		try {
			StringBuilder sb1 = new StringBuilder();
			StringBuilder sb2 = new StringBuilder();
			sb1.append("select  bzn.title , bzn.content , user.username,  bzn.id ,user.id ,bzn.createDatetime , bzn.updateDatetime , assigned.id , assigned.usr_user.id from Bzn_questionassigned  assigned  left join  assigned.bzn_question bzn left join bzn.usr_user user   where  bzn.flag = 0 and assigned.usr_user.id = "+bzn_questionassigned.getUsr_user().getId());
			sb2.append("select count(bzn) from Bzn_questionassigned  assigned  left join  assigned.bzn_question bzn left join bzn.usr_user user   where  bzn.flag = 0 and assigned.usr_user.id = "+bzn_questionassigned.getUsr_user().getId());//
			sb1.append(" order by bzn.id desc");
			List<Object[]> resultlist = (List<Object[]>) this.getPageList(page, sb1.toString());	
			List<Object[]> newlist = new ArrayList<Object[]>();
			for (Object[] objects : resultlist) {
				Object[] newObjects = new Object[9];
				for (int i = 0; i < newObjects.length-1; i++) {
					newObjects[i] = objects[i];
				}
				newObjects[5] = new TimeDiff().getTimeDiff(objects[5]+"", objects[6]+"");
				newlist.add(newObjects);
			}
			JSONArray json = new ConverntJsonData().getJsonData(newlist);
			JSONArray newJson = new JSONArray();
			newJson.put(this.getNum(page, sb2.toString()));
			for (int i = 0; i < json.length(); i++) {
				newJson.put(json.get(i));
			}
			JsonData jsonData = new JsonData();
			jsonData.setJsonData(newJson.toString());
			System.out.println(newJson);
			return jsonData;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean delBzn_questionassignedByQuestionId(Bzn_question bzn_question){
		return updateDataByHQL("delete from Bzn_questionassigned assigned where assigned.bzn_question.id ="+bzn_question.getId());
	}
}